package com.finance.system.support.utils;


import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.UUID;

public class RequestUtils {


    public static final String REQUEST_ID = "requestId";

    public static String getRequestId(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if(attributes == null ){
            return null;
        }
        Object attribute = attributes
                .getAttribute(REQUEST_ID, RequestAttributes.SCOPE_REQUEST);
        if(attribute == null){
            String requestId = UUID.randomUUID().toString();
            RequestContextHolder.getRequestAttributes().setAttribute(REQUEST_ID,
                    requestId ,RequestAttributes.SCOPE_REQUEST);
            return requestId;
        }
        return (String)attribute;
    }

    public static void putRequestId(String requestId){
        RequestContextHolder.getRequestAttributes()
                .setAttribute(REQUEST_ID,requestId, RequestAttributes.SCOPE_REQUEST);
    }
}
